const { TimeRange, mapAttributes } = require('../../util')

const filterByTimeRange = (arr, timeRange) => {
  return arr.filter(item => {
    const createdAt = item.get('createdAt').getTime()
    const start = timeRange[0].getTime()
    const end = timeRange[1].getTime()
    return createdAt >= start && createdAt <= end
  })
}

const firstLetterToUpperCase = str => str.replace(/\b(\w)|\s(\w)/g, m => m.toUpperCase())

const count = async (query, keys) => {
  const RECENTDAY = 30
  const timeRange = new TimeRange() // 时间段
  const lastThirtyDay = timeRange.currentDays(RECENTDAY)

  const findModelList = await query.greaterThanOrEqualTo('createdAt', lastThirtyDay[0]).lessThanOrEqualTo('createdAt', lastThirtyDay[1]).find()

  const times = {
    thisDay: timeRange.thisDay(),
    lastDay: timeRange.lastDay(),
    beforeYesterday: timeRange.recentRange(2, 1),
    lastSevenDay: timeRange.currentDays(7),
    lastThirtyDay
  }

  return Object.keys(times).reduce((prev, time) => {
    const lists = filterByTimeRange(findModelList, times[time])
    lists.reduce((lPrev, cur) => {
      keys.forEach(key => {
        const name = `${time}${firstLetterToUpperCase(key)}`
        lPrev[name] = (lPrev[name] || 0) + (cur.get(key) || 0)
      })
      return lPrev
    }, prev)
    return prev
  }, {})
}

Parse.Cloud.define('rsOrderCount', async (req, res) => {
  const result = await count(new Parse.Query('RcOrderCount').equalTo('type', 1), ['price', 'number', 'shareMoney'])
  const total = await new Parse.Query('RcOrderCount').equalTo('type', 0).first()
  if (total) {
    result.totalPrice = total.get('price')
    result.totalNumber = total.get('number')
    result.totalShareMoney = total.get('shareMoney')
  }
  res.success([result])
})

Parse.Cloud.define('rsCashCount', async (req, res) => {
  const cash = await new Parse.Query('RcCashCount').first()
  const result = []
  if (cash) {
    result.push(mapAttributes(cash, ['remaining', 'total', 'memberCount', 'lock', 'success', 'successCount']))
  }
  res.success(result)
})

Parse.Cloud.define('rsModelCount', async (req, res) => {
  const { model } = req.params
  const RECENTDAY = 30
  const timeRange = new TimeRange() // 时间段
  const times = {
    thisDay: timeRange.thisDay(),
    lastDay: timeRange.lastDay(),
    beforeYesterday: timeRange.recentRange(2, 1),
    lastSevenDay: timeRange.currentDays(7),
    lastThirtyDay: timeRange.currentDays(RECENTDAY)
  }
  const timeKeys = Object.keys(times)
  const counts = timeKeys.map(time => new Parse.Query(model).greaterThanOrEqualTo('createdAt', times[time][0]).lessThanOrEqualTo('createdAt', times[time][1]).count())
  const total = await new Parse.Query(model).count()
  const result = {}
  for (let i = 0; i < timeKeys.length; i++) {
    result[timeKeys[i]] = await counts[i]
  }
  result.total = total
  res.success([result])
})
